<template>
  <div class="quiz-result">
    <div class="page-header">
      <div class="header-top">
        <button class="back-btn" @click="goBack">← 返回</button>
        <h1>答题结果</h1>
        <div class="spacer"></div>
      </div>
    </div>
    
    <div class="result-content">
      <!-- 保持原来的 result-card，但添加内部滚动 -->
      <div class="result-card" :class="{ correct: isCorrect, incorrect: !isCorrect }">
        <div class="result-icon">
          <span v-if="isCorrect">🎉</span>
          <span v-else>❌</span>
        </div>
        <h2>{{ isCorrect ? '回答正确!' : '回答错误!' }}</h2>
        <p class="result-message">{{ resultMessage }}</p>
        
        <div class="score-info" v-if="scoreEarned > 0">
          <p>本次得分: <span class="score">{{ scoreEarned }}</span> 碳积分</p>
        </div>
        
        <div class="answer-details" v-if="selectedOptionContent || correctOptionContent">
          <div class="selected-answer" v-if="selectedOptionContent">
            <h3>你的答案:</h3>
            <p :class="{ wrong: !isCorrect }">{{ selectedOptionContent }}</p>
          </div>
          
          <div class="correct-answer" v-if="correctOptionContent && !isCorrect">
            <h3>正确答案:</h3>
            <p class="correct">{{ correctOptionContent }}</p>
          </div>
        </div>
        
        <div class="explanation" v-if="explanation">
          <h3>解析:</h3>
          <p>{{ explanation }}</p>
        </div>
        
        <!-- 添加用户积分和排名信息 -->
        <div class="user-stats" v-if="totalScore > 0 || currentRank > 0">
          <h3>用户统计:</h3>
          <p>总积分: {{ totalScore }}</p>
          <p>当前排名: {{ currentRank }}</p>
        </div>
      </div>
      
      <div class="actions">
        <button class="review-btn" @click="reviewQuestion">回顾题目</button>
        <button class="next-btn" @click="nextAction">继续挑战</button>
        <button class="return-btn" @click="returnToLevelDetail">返回关卡详情</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getQuestionDetail, submitAnswer, getLevelDetail, getLevelProgress } from '../api/challenge'

// 路由
const route = useRoute()
const router = useRouter()

// 数据状态
const isCorrect = ref(false)
const scoreEarned = ref(0)
const selectedOptionContent = ref('')
const correctOptionContent = ref('')
const explanation = ref('')
const totalScore = ref(0) // 用户总积分
const currentRank = ref(0) // 用户当前排名
const loading = ref(true)
const error = ref('')
const totalQuestions = ref(0) // 总题目数

const triggerPointsToast = inject<(delta: number) => void>('triggerPointsToast')

// 计算属性
const resultMessage = computed(() => {
  return isCorrect.value ? '恭喜你答对了这道题！' : '很遗憾答错了，再接再厉！'
})

// 从路由参数获取数据
const levelId = route.query.levelId ? parseInt(route.query.levelId as string) : 0
const questionId = route.query.questionId ? parseInt(route.query.questionId as string) : 0
const selectedOptionId = route.query.selectedOptionId ? parseInt(route.query.selectedOptionId as string) : 0
const questionIndex = route.query.questionIndex ? parseInt(route.query.questionIndex as string) : 0 // 添加题目索引

// 提交答案并获取结果
const submitAnswerAndGetResult = async () => {
  try {
    console.log('[QuizResult] [DEBUG] 开始提交答案:', { questionId, selectedOptionId })
    
    // 检查必要参数
    if (!questionId || !selectedOptionId) {
      console.warn('[QuizResult] [DEBUG] 缺少必要参数:', { questionId, selectedOptionId })
      return
    }
    
    // 提交答案
    const response: any = await submitAnswer(questionId, selectedOptionId)
    console.log('[QuizResult] [DEBUG] 提交答案响应:', response)
    
    // 处理响应结果
    if (response && typeof response === 'object' && 'success' in response && response.success) {
      // 从响应中获取结果数据
      isCorrect.value = response.data?.is_correct || false
      scoreEarned.value = response.data?.score_earned || 0
      totalScore.value = response.data?.total_score || 0
      currentRank.value = response.data?.current_rank || 0
      explanation.value = response.data?.explanation || ''
      correctOptionContent.value = response.data?.correct_option_content || ''
      selectedOptionContent.value = response.data?.selected_option_content || ''
      
      console.log('[QuizResult] [DEBUG] 答题结果:', { 
        isCorrect: isCorrect.value, 
        scoreEarned: scoreEarned.value,
        totalScore: totalScore.value,
        currentRank: currentRank.value
      })
      if (scoreEarned.value > 0) {
        triggerPointsToast?.(scoreEarned.value)
      }
    } else {
      // 提交失败
      const message = typeof response === 'object' && 'message' in response ? response.message : '提交答案失败'
      console.error('[QuizResult] [ERROR] 提交答案失败:', message)
      error.value = message || '提交答案失败'
    }
  } catch (err: any) {
    console.error('[QuizResult] [ERROR] 提交答案异常:', err)
    error.value = err.message || '提交答案时发生错误'
  }
}

// 回顾题目
const reviewQuestion = () => {
  if (levelId && questionId) {
    router.push(`/level-quiz/${levelId}?questionIndex=${questionIndex}`)
  }
}

// 下一步操作 - 跳转到下一题或返回关卡详情页
const nextAction = async () => {
  // 如果有下一题，则跳转到下一题
  if (levelId && questionIndex >= 0) {
    // 检查是否还有下一题
    const nextQuestionIndex = questionIndex + 1;
    
    // 如果还没获取总题目数，先获取
    if (totalQuestions.value === 0) {
      try {
        const response = await getLevelDetail(levelId);
        if (response && response.data && response.data.level) {
          totalQuestions.value = response.data.level.questions?.length || 0;
        }
      } catch (err) {
        console.error('获取关卡详情失败:', err);
        // 默认假设10题
        totalQuestions.value = 10;
      }
    }
    
    if (nextQuestionIndex < totalQuestions.value) {
      router.push(`/level-quiz/${levelId}?questionIndex=${nextQuestionIndex}`);
    } else {
      // 如果没有下一题，返回关卡详情页
      router.push(`/level-detail/${levelId}`);
    }
  } else {
    // 否则返回关卡详情页
    router.push(`/level-detail/${levelId}`);
  }
}

// 返回关卡详情页
const returnToLevelDetail = async () => {
  // 在返回前重新加载关卡进度，确保状态是最新的
  try {
    await getLevelProgress(levelId);
  } catch (err) {
    console.error('[QuizResult] [ERROR] 重新加载关卡进度失败:', err);
  }
  router.push(`/level-detail/${levelId}`);
}

// 返回上一页
const goBack = () => {
  router.go(-1);
}

// 加载题目详情
const loadQuestionDetails = async () => {
  try {
    if (!questionId) return
    
    loading.value = true
    const response = await getQuestionDetail(questionId)
    
    if (response && typeof response === 'object' && 'success' in response && response.success && 'data' in response && response.data) {
      const questionData = response.data
      
      // 查找选中的选项内容（如果还没有）
      if (!selectedOptionContent.value && selectedOptionId && questionData.options) {
        const selectedOption = questionData.options.find((opt: any) => opt.option_id === selectedOptionId)
        if (selectedOption) {
          selectedOptionContent.value = selectedOption.content
        }
      }
      
      // 查找正确答案内容（如果还没有）
      if (!correctOptionContent.value && questionData.options) {
        const correctOption = questionData.options.find((opt: any) => opt.option_id === questionData.correct_option_id)
        if (correctOption) {
          correctOptionContent.value = correctOption.content
        }
      }
      
      // 设置解析（如果还没有）
      if (!explanation.value && questionData.explanation) {
        explanation.value = questionData.explanation
      }
    }
  } catch (err: any) {
    console.error('[QuizResult] [ERROR] 加载题目详情失败:', err)
    error.value = err.message || '加载失败'
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  // 提交答案并获取结果
  submitAnswerAndGetResult().then(() => {
    // 答案提交完成后加载题目详情（作为备份）
    loadQuestionDetails()
  })
})
</script>

<style scoped>
.quiz-result {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 1.8rem;
  margin: 0;
  color: #2c3e50;
  flex: 1;
  text-align: center;
  padding: 0 20px;
}

.back-btn {
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: bold;
  white-space: nowrap;
  background-color: #f8f9fa;
  color: #495057;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #e9ecef;
}

.spacer {
  width: 100px;
}

.result-content {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.result-card {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  padding: 40px;
  text-align: center;
  box-sizing: border-box;
  transition: all 0.3s;
  max-height: 70vh;
  overflow-y: auto;
}

.result-card.correct {
  border: 3px solid #42b983;
}

.result-card.incorrect {
  border: 3px solid #ff6b35;
}

.result-icon {
  font-size: 4rem;
  margin-bottom: 20px;
}

.result-card h2 {
  color: #2c3e50;
  margin: 0 0 15px 0;
  font-size: 2rem;
}

.result-message {
  color: #6c757d;
  font-size: 1.2rem;
  margin-bottom: 30px;
}

.score-info {
  background-color: #e8f5ee;
  padding: 15px;
  border-radius: 10px;
  margin-bottom: 30px;
}

.score {
  font-weight: bold;
  color: #42b983;
  font-size: 1.5rem;
}

.answer-details {
  text-align: left;
  margin-bottom: 30px;
}

.answer-details h3 {
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.answer-details p {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin: 0 0 15px 0;
  font-size: 1.1rem;
}

.answer-details .correct {
  background-color: #e8f5ee;
  color: #42b983;
  border: 1px solid #42b983;
}

.answer-details .wrong {
  background-color: #fce8e6;
  color: #ff6b35;
  border: 1px solid #ff6b35;
}

.explanation {
  text-align: left;
  background-color: #e9f7ef;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 30px;
}

.explanation h3 {
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.explanation p {
  margin: 0;
  color: #495057;
  line-height: 1.6;
}

/* 用户统计信息样式 */
.user-stats {
  text-align: left;
  background-color: #f0f8ff;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 30px;
}

.user-stats h3 {
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.user-stats p {
  margin: 10px 0;
  padding: 8px;
  background-color: #e6f7ff;
  border-radius: 6px;
  font-weight: 500;
}

.actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}

.review-btn, .next-btn, .return-btn {
  padding: 12px 30px;
  border-radius: 25px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.review-btn {
  background-color: #f8f9fa;
  color: #495057;
}

.review-btn:hover {
  background-color: #e9ecef;
  transform: scale(1.05);
}

.next-btn {
  background-color: #42b983;
  color: white;
}

.next-btn:hover {
  background-color: #359c6d;
  transform: scale(1.05);
}

.return-btn {
  background-color: #6c757d;
  color: white;
}

.return-btn:hover {
  background-color: #5a6268;
  transform: scale(1.05);
}

@media (max-width: 768px) {
  .quiz-result {
    padding: 15px;
  }
  
  .page-header {
    padding: 15px;
  }
  
  .page-header h1 {
    font-size: 1.5rem;
  }
  
  .result-card {
    padding: 30px 20px;
  }
  
  .result-icon {
    font-size: 3rem;
  }
  
  .result-card h2 {
    font-size: 1.5rem;
  }
  
  .actions {
    flex-direction: column;
    gap: 15px;
  }
  
  .review-btn, .next-btn, .return-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .quiz-result {
    padding: 10px;
  }
  
  .header-top {
    flex-direction: column;
    gap: 15px;
  }
  
  .page-header h1 {
    font-size: 1.3rem;
    padding: 0;
  }
  
  .back-btn {
    padding: 8px 15px;
    font-size: 0.9rem;
  }
  
  .result-card {
    padding: 20px 15px;
  }
  
  .result-icon {
    font-size: 2.5rem;
  }
  
  .result-card h2 {
    font-size: 1.3rem;
  }
}
</style>
